import { GlobalStore } from "@/stores";
import "./index.scss";
import { AuthStore } from "@/stores/modules/auth";
import { PublicStore } from "@/stores/modules/public";
import { MessageHandler } from "element-plus";
// import { ComponentInternalInstance, getCurrentInstance } from "vue";
import QrcodeVue from "qrcode.vue";
import { useRouter } from "vue-router";
import { getHome } from "../../../utils/routerUtil";
const LoginScan = defineComponent({
	setup() {
		// const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const authStore = AuthStore();
		const publicStore = PublicStore();
		const globalStore = GlobalStore();
		const router = useRouter();
		const qrCodeValue = ref("");
		const t = ref();
		onMounted(() => {
			authStore.logout();
			resetCode();
		});
		const resetCode = () => {
			if (t.value) {
				clearInterval(t.value);
			}
			qrCodeValue.value = Date.now() + "";
			login();
			setTimeout(() => {
				clearInterval(t.value);
				t.value = "";
			}, 300000);
		};
		const login = () => {
			t.value = setInterval(async () => {
				const err: MessageHandler | string | undefined = await authStore.login({ qrCode: qrCodeValue.value });
				if (err != null) {
					if (err.toString() == "二维码无效") {
						return;
					} else {
						clearInterval(t.value);
						t.value = "";
						return;
					}
				}

				// 默认主页无法访问时导致系统无法使用，暂不启用
				if (globalStore.setting.home.startsWith("http")) {
					let token = "";
					if (RegExp(/\?.+=.*/).test(globalStore.setting.home)) {
						token = `&token=${publicStore.token}`;
					} else {
						token = `?token=${publicStore.token}`;
					}
					let server = globalStore.setting.home + token;
					window.location.href = server;
				} else {
					router.push(getHome());
				}
			}, 1000);
		};
		onBeforeUnmount(() => {
			clearInterval(t.value);
		});
		return () => {
			return (
				<div class="flex flex-col items-center">
					<div class="text-slate-500">请使用微信扫一扫</div>
					{!t.value ? (
						<div class="text-xl text-red-600" style="position: absolute;top: 45%;">
							二维码失效，点击刷新
						</div>
					) : (
						""
					)}
					<QrcodeVue
						onClick={() => {
							resetCode();
						}}
						value={"https://mapall.cn/xw?type=auth&qrCode=" + qrCodeValue.value}
						size="200"
						level="H"
						class={`mt-6 mb-12 qrcode ${t.value ? "" : "blur-sm opacity-30"}`}
					></QrcodeVue>
				</div>
			);
		};
	}
});
export default LoginScan;
